<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <div class="title">水果商城数据大屏</div>
      <div class="time">{{ currentTime }}</div>
    </div>

    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="8">
        <div class="statistic-card">
          <el-statistic :value="statistics.totalSales" :precision="2">
            <template #title>
              <div class="card-title">总销售额</div>
            </template>
            <template #prefix>
              <span class="prefix">¥</span>
            </template>
          </el-statistic>
        </div>
      </el-col>

      <el-col :span="8">
        <div class="statistic-card">
          <el-statistic :value="statistics.orderCount" :precision="0">
            <template #title>
              <div class="card-title">订单数量</div>
            </template>
          </el-statistic>
        </div>
      </el-col>

      <el-col :span="8">
        <div class="statistic-card">
          <el-statistic :value="statistics.visitorCount" :precision="0">
            <template #title>
              <div class="card-title">新增用户</div>
            </template>
          </el-statistic>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-container">
      <el-col :span="10">
        <el-card class="chart-card">
          <div class="chart-title">热销商品 TOP5</div>
          <div ref="hotProductsChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="14">
        <el-card class="chart-card">
          <div class="chart-title">订单状态占比</div>
          <div ref="orderStatusChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-container">
      <el-col :span="24">
        <el-card class="chart-card">
          <div class="chart-title">销售趋势</div>
          <div ref="salesChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import { getWeeklySalesStats, getHotFruitRanking, getOrderStatusDistribution, getDailySalesTrend } from '@/api/home'

const currentTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
let timeTimer
let dataTimer

const statistics = ref({
  totalSales: 0,
  orderCount: 0,
  visitorCount: 0,
  hotProducts: [],
  salesTrend: []
})

const salesChart = ref(null)
const orderStatusChart = ref(null)
const hotProductsChart = ref(null)

const updateTime = () => {
  currentTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
}

const fetchStatistics = async () => {
  try {
    const salesRes = await getWeeklySalesStats()
    if (salesRes.data.code === 200) {
      const { totalSalesAmount, totalOrderCount, newUserCount } = salesRes.data.data
      statistics.value = {
        ...statistics.value,
        totalSales: totalSalesAmount,
        orderCount: totalOrderCount,
        visitorCount: newUserCount
      }
    }

    const hotProductsRes = await getHotFruitRanking()
    if (hotProductsRes.data.code === 200) {
      statistics.value.hotProducts = hotProductsRes.data.data
      nextTick(() => {
        initHotProductsChart()
      })
    }

    const orderStatusRes = await getOrderStatusDistribution()
    if (orderStatusRes.data.code === 200) {
      nextTick(() => {
        initOrderStatusChart(orderStatusRes.data.data)
      })
    }

    const salesTrendRes = await getDailySalesTrend()
    if (salesTrendRes.data.code === 200) {
      statistics.value.salesTrend = salesTrendRes.data.data
      nextTick(() => {
        initSalesChart()
      })
    }
  } catch (error) {
  }
}

const initSalesChart = () => {
  const chart = echarts.init(salesChart.value)
  
  // 准备数据
  const dates = statistics.value.salesTrend.map(item => item.date) || ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  const values = statistics.value.salesTrend.map(item => item.amount) || [0, 0, 0, 0, 0, 0, 0]
  
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.2)'
        }
      },
      backgroundColor: 'rgba(255, 255, 255, 0.1)',
      borderColor: 'rgba(255, 255, 255, 0.2)',
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      top: '10%',
      left: '3%',
      right: '3%',
      bottom: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)',
          width: 2
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.8)',
        fontSize: 14
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.15)',
          width: 1.5
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.8)',
        fontSize: 14
      }
    },
    series: [
      {
        name: '销售额',
        type: 'bar',
        barWidth: '60%',
        data: values,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#67F0F3' },
            { offset: 1, color: '#32D5F9' }
          ]),
          borderRadius: [6, 6, 0, 0]
        }
      },
      {
        name: '销售趋势',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        showSymbol: false,
        lineStyle: {
          width: 3,
          color: '#FF7B7B'
        },
        itemStyle: {
          color: '#FF7B7B',
          borderColor: '#FF7B7B',
          borderWidth: 2
        },
        emphasis: {
          scale: true
        },
        data: values
      }
    ]
  }
  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

const initOrderStatusChart = (orderStatusData = {}) => {
  const chart = echarts.init(orderStatusChart.value)
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)',
      backgroundColor: 'rgba(255, 255, 255, 0.1)',
      borderColor: 'rgba(255, 255, 255, 0.2)',
      textStyle: {
        color: '#fff'
      }
    },
    legend: {
      orient: 'vertical',
      right: '2%',
      top: 'center',
      textStyle: {
        color: 'rgba(255, 255, 255, 0.9)',
        fontSize: 14
      },
      icon: 'circle'
    },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: ['48%', '80%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderColor: 'rgba(0, 0, 0, 0.1)',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}\n{c}',
          color: 'rgba(255, 255, 255, 1)',
          fontSize: 13,
          fontWeight: 'bold',
          lineHeight: 18,
          alignTo: 'edge',
          edgeDistance: '25%',
          distanceToLabelLine: 5
        },
        labelLine: {
          show: true,
          length: 18,
          length2: 6,
          smooth: true,
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.5)',
            width: 1.5
          }
        },
        data: [
          { 
            value: orderStatusData.pendingPaymentCount || 0, 
            name: '待付款', 
            itemStyle: { color: '#77F0F3' }
          },
          { 
            value: orderStatusData.pendingShipmentCount || 0, 
            name: '待发货', 
            itemStyle: { color: '#5FACFE' }
          },
          { 
            value: orderStatusData.pendingReceiptCount || 0, 
            name: '待收货', 
            itemStyle: { color: '#53F98B' }
          },
          { 
            value: orderStatusData.completedCount || 0, 
            name: '已完成', 
            itemStyle: { color: '#42D5F9' }
          },
          { 
            value: orderStatusData.cancelledCount || 0, 
            name: '已取消', 
            itemStyle: { color: '#FF7B7B' }
          },
          { 
            value: orderStatusData.pendingReviewCount || 0, 
            name: '待评价', 
            itemStyle: { color: '#B19CE1' }
          },
          { 
            value: orderStatusData.reviewedCount || 0, 
            name: '已评价', 
            itemStyle: { color: '#5FACFE' }
          }
        ]
      }
    ]
  }
  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

const initHotProductsChart = () => {
  const chart = echarts.init(hotProductsChart.value)
  const colors = [
    ['#77F0F3', '#42D5F9'],
    ['#5FACFE', '#10F2FE'],
    ['#53F98B', '#48F9E7'],
    ['#42D5F9', '#77F0F3'],
    ['#5FACFE', '#42D5F9']
  ]
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      backgroundColor: 'rgba(255, 255, 255, 0.1)',
      borderColor: 'rgba(255, 255, 255, 0.2)',
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      top: '5%',
      left: '3%',
      right: '12%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)',
          width: 2
        }
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.15)',
          width: 1.5,
          type: 'solid'
        }
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.8)',
        fontSize: 14
      }
    },
    yAxis: {
      type: 'category',
      data: statistics.value.hotProducts.map(item => item.fruitName),
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)',
          width: 2
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.9)',
        fontSize: 14,
        margin: 18,
        fontWeight: 'bold'
      }
    },
    series: [
      {
        name: '销量',
        type: 'bar',
        barWidth: '65%',
        data: statistics.value.hotProducts.map((item, index) => ({
          value: item.salesQuantity,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              { offset: 0, color: colors[index][0] },
              { offset: 1, color: colors[index][1] }
            ])
          }
        })),
        label: {
          show: true,
          position: 'right',
          color: 'rgba(255, 255, 255, 1)',
          fontSize: 14,
          fontWeight: 'bold',
          formatter: '{c}',
          distance: 12
        },
        itemStyle: {
          borderRadius: [0, 6, 6, 0]
        }
      }
    ]
  }
  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

onMounted(() => {
  fetchStatistics()
  initSalesChart()
  initOrderStatusChart()
  initHotProductsChart()
  
  timeTimer = setInterval(updateTime, 1000)
  dataTimer = setInterval(fetchStatistics, 60000)
})

onUnmounted(() => {
  if (dataTimer) {
    clearInterval(dataTimer)
  }
  if (timeTimer) {
    clearInterval(timeTimer)
  }
})
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #1a2b3c 0%, #2c547a 100%);
  color: #ffffff;
  position: relative;
  overflow: hidden;
  border-radius: 15px;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
  position: relative;
}

.title {
  font-size: 30px;
  font-weight: bold;
  background: linear-gradient(90deg, #77F0F3 0%, #42D5F9 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  position: relative;
  text-shadow: 0 0 20px rgba(103, 224, 227, 0.5);
}

.time {
  font-size: 24px;
  color: #77F0F3;
  text-shadow: 0 0 10px rgba(103, 224, 227, 0.3);
  letter-spacing: 1px;
  background: rgba(255, 255, 255, 0.05);
  padding: 8px 15px;
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.time::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 8px;
  padding: 1px;
  background: linear-gradient(90deg, 
    transparent,
    transparent,
    #77F0F3,
    transparent,
    transparent
  );
  -webkit-mask: 
    linear-gradient(#fff 0 0) content-box, 
    linear-gradient(#fff 0 0);
  -webkit-mask-composite: xor;
  mask-composite: exclude;
  animation: borderFlow 3s linear infinite;
  pointer-events: none;
}

@keyframes borderFlow {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

.statistics-cards {
  margin-bottom: 25px;
}

.statistic-card {
  height: 100%;
  padding: 20px;
  border-radius: 15px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;
}

.statistic-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 15px;
  padding: 2px;
  background: linear-gradient(90deg, 
    transparent,
    transparent,
    #77F0F3,
    transparent,
    transparent
  );
  -webkit-mask: 
    linear-gradient(#fff 0 0) content-box, 
    linear-gradient(#fff 0 0);
  -webkit-mask-composite: xor;
  mask-composite: exclude;
  animation: borderFlow 3s linear infinite;
  pointer-events: none;
}

.card-title {
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
}

.prefix {
  font-size: 20px;
  margin-right: 4px;
  color: #ffffff;
}

.charts-container {
  margin-bottom: 25px;
}

.chart-card {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  position: relative;
  overflow: hidden;
  height: 100%;
}

.chart-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 15px;
  padding: 2px;
  background: linear-gradient(90deg,
    transparent,
    transparent,
    #77F0F3,
    transparent,
    transparent
  );
  background-size: 200% 100%;
  -webkit-mask: 
    linear-gradient(#fff 0 0) content-box, 
    linear-gradient(#fff 0 0);
  -webkit-mask-composite: xor;
  mask-composite: exclude;
  animation: borderFlow 4s linear infinite;
  pointer-events: none;
}

.chart-title {
  font-size: 18px;
  color: #77F0F3;
  margin-bottom: 10px;
  padding: 12px 15px;
  border-bottom: 1px solid rgba(119, 240, 243, 0.2);
  position: relative;
}

.chart {
  height: 400px;
  width: 100%;
  padding: 10px;
}

:deep(.el-card) {
  background: transparent;
  border: none;
  color: #ffffff;
}

:deep(.el-card__body) {
  padding: 10px;
}

.chart-card:first-child .chart {
  height: 400px;
}

.chart-card:last-child .chart {
  height: 400px;
}

.current-time {
  position: absolute;
  top: 20px;
  right: 20px;
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
}

:deep(.el-statistic) {
  --el-statistic-content-font-size: 36px;
  --el-statistic-title-font-size: 16px;
  --el-statistic-content-color: #77F0F3;
}
</style> 